﻿using Basic.FlowModel.DB;
using Basic.FlowRemoteModel.NodeFormData.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FlowDAL.lmpl
{
    internal class FlowFormDataRelationDAL : BasicDAL<DBFlowFormDataRelation, long>, IFlowFormDataRelationDAL
    {
        public FlowFormDataRelationDAL ( IRepository<DBFlowFormDataRelation> basicDAL ) : base(basicDAL, "form.data.relation")
        {
        }
        public void Add ( long flowId, long nodeId, DataRelation[] adds )
        {
            DBFlowFormDataRelation[] data = adds.ConvertAll(a => new DBFlowFormDataRelation
            {
                ColId = a.ColId,
                FlowId = flowId,
                Id = IdentityHelper.CreateId(),
                FormId = a.FormId,
                Keywords = a.Keywords,
                NodeId = nodeId,
                ToColId = a.ToColId
            });
            this._BasicDAL.Insert(data);
        }
        public void Set ( long flowId, long nodeId, DataRelation[] adds )
        {
            if ( adds.IsNull() )
            {
                if ( !this._BasicDAL.Delete(a => a.NodeId == nodeId) )
                {
                    throw new ErrorException("flow.form.data.relation.delete.fail");
                }
                return;
            }
            DBFlowFormDataRelation[] datas = adds.ConvertAll(a => new DBFlowFormDataRelation
            {
                ColId = a.ColId,
                FlowId = flowId,
                Id = IdentityHelper.CreateId(),
                FormId = a.FormId,
                Keywords = a.Keywords,
                NodeId = nodeId,
                ToColId = a.ToColId
            });
            ISqlQueue<DBFlowFormDataRelation> queue = this._BasicDAL.BeginQueue();
            queue.Delete(a => a.NodeId == nodeId);
            queue.Insert(datas);
            _ = queue.Submit();
        }
    }
}
